package com.ztom.v2;

/**
 * @author ZhangTao
 */
public class Code64SearchA2dMatrix {

    public boolean searchMatrix1(int[][] matrix, int target) {
        for (int[] ints : matrix) {
            if (search(ints, target) != -1) {
                return true;
            }
        }
        return false;
    }

    public int search(int[] nums, int t) {
        int l = 0;
        int r = nums.length - 1;
        while (l <= r) {
            int mid = l + ((r - l) >> 1);
            if (nums[mid] < t) {
                l = mid + 1;
            } else if (nums[mid] > t) {
                r = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }


    public boolean searchMatrix(int[][] matrix, int target) {
        // 将所有行拼接就是一个递增数组, 一次二分
        int m = matrix.length;
        int n = matrix[0].length;
        int l = 0;
        int r = m * n - 1;
        while (l <= r) {
            int mid = l + ((r - l) >> 1);
            // 换算坐标
            int row = mid / n;
            int col = mid % n;
            if (matrix[row][col] == target) {
                return true;
            } else if (matrix[row][col] < target) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        return false;
    }
}
